package com.lm.sm.example;
import org.bouncycastle.crypto.engines.SM4Engine;
import org.bouncycastle.crypto.modes.CBCBlockCipher;
import org.bouncycastle.crypto.paddings.*;
import org.bouncycastle.crypto.params.KeyParameter;
import org.bouncycastle.crypto.params.ParametersWithIV;
import org.bouncycastle.util.encoders.Hex;

public class SM4Example {
    private static final byte[] KEY = Hex.decode("0123456789abcdeffedcba9876543210");
    private static final byte[] IV = Hex.decode("00000000000000000000000000000000");

    public static String encrypt(String plainText) throws Exception {
        PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new SM4Engine()));
        cipher.init(true, new ParametersWithIV(new KeyParameter(KEY), IV));
        byte[] input = plainText.getBytes("UTF-8");
        byte[] output = new byte[cipher.getOutputSize(input.length)];
        int len = cipher.processBytes(input, 0, input.length, output, 0);
        len += cipher.doFinal(output, len);
        return Hex.toHexString(output, 0, len);
    }

    public static String decrypt(String cipherTextHex) throws Exception {
        byte[] cipherText = Hex.decode(cipherTextHex);
        PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new SM4Engine()));
        cipher.init(false, new ParametersWithIV(new KeyParameter(KEY), IV));
        byte[] output = new byte[cipher.getOutputSize(cipherText.length)];
        int len = cipher.processBytes(cipherText, 0, cipherText.length, output, 0);
        len += cipher.doFinal(output, len);
        return new String(output, 0, len, "UTF-8");
    }

    public static void main(String[] args) throws Exception {
        String plainText = "国密SM4对称加密";
        String encrypted = encrypt(plainText);
        String decrypted = decrypt(encrypted);
        System.out.println("密文: " + encrypted);
        System.out.println("解密: " + decrypted);
    }
}
